const express = require('express')
const createBundleRenderer = require('./bundleRenderer')
const config = require('../configure')

const app = express()

const getVuePage = async (req, res, next) => {
  try {
    const renderer = await createBundleRenderer()

    renderer.renderToString(
      { url: req.url },
      (err, html) => {
        if (err) {
          // 获取不到页面给下个程序获取
          console.error(err)
          next()
        } else {
          res.type('html')
          res.end(html)
        }
      }
    )
  } catch (e) {
    console.error(e)
    res.status(500)
    res.end('Server Not Ready Yet!')
  }
}

let expressStatic
const switchOther = async (...args) => {
  const { checkServer, server } = require('./proxy')
  if (await checkServer()) {
    server(...args)
  } else {
    expressStatic = expressStatic || 
      express.static(config.clientOutpueDir, { index: false })

    expressStatic(...args)
  }
}

app.get(
  '*', 
  getVuePage,
  // index.html不能静态获取因为要渲染
  !config.isDev ? 
    express.static(config.clientOutpueDir, { index: false }) :
    switchOther
)

app.listen(
  config.rendererServerPort,
  () => {
    console.log(`server listening on ${config.rendererServerPort} port`)
  }
)
